<?php

class SoundcloudPlayer {
	
	public $soundcloud_username;
	
	public function execute() {
		$action = $_GET ['action'];
		
		$host = $GLOBALS ["host"];
		$login = $GLOBALS ["login"];
		$pass = $GLOBALS ["pass"];
		$database = $GLOBALS ["database"];
		$this->soundcloud_username = $GLOBALS ["soundcloud_username"];
		
		mysql_connect ( $host, $login, $pass );
		mysql_select_db ( $database );
		
		if ($action == "tracks") {
			$this->getTracks ();
		} elseif ($action == "tags") {
			$this->getTags ();
		} elseif ($action == "refresh") {
			$this->refresh ();
		} elseif ($action == "vote") {
			$this->vote ();
		} else {
			echo "not a valid action";
		}
		mysql_close ();
	}
	
	private function getTracks() {
		header('Content-Type: text/xml');
		$query = "SELECT tracks.track_id, tracks.title, tracks.artist, tracks.duration, tracks.stream_url, tracks.permalink, tracks.created_at, AVG( rating.rating ) AS rating FROM tracks LEFT OUTER JOIN rating on rating.track_id = tracks.track_id GROUP BY tracks.track_id ORDER BY tracks.created_at DESC";
		$result = mysql_query ( $query );
		if ($result == false or mysql_num_rows ( $result ) < 1) {
			echo "no data found";
		} else {
			$dom = new DomDocument ( '1.0' );
			$tracks = $dom->appendChild ( $dom->createElement ( 'tracks' ) );
			while ( $row = mysql_fetch_array ( $result, MYSQL_ASSOC ) ) {
				$track = $tracks->appendChild ( $dom->createElement ( 'track' ) );
				$track_id = $dom->createAttribute ( "track_id" );
				$track_id_value = (int) $row ["track_id"];
				$track_id->appendChild ( $dom->createTextNode ( $track_id_value ) );
				$track->appendChild ( $track_id );
				$title = $dom->createAttribute ( "title" );
				$title->appendChild ( $dom->createTextNode ( utf8_encode($row ["title"]) ) );
				$track->appendChild ( $title );
				$artist = $dom->createAttribute ( "artist" );
				$artist->appendChild ( $dom->createTextNode ( utf8_encode($row ["artist"]) ) );
				$track->appendChild ( $artist );
				$duration = $dom->createAttribute ( "duration" );
				$duration_value = date("i:s", $row ["duration"] / 1000 );
				$duration->appendChild ( $dom->createTextNode ( $duration_value ) );
				$track->appendChild ( $duration );
				$stream_url = $dom->createAttribute ( "stream_url" );
				$stream_url->appendChild ( $dom->createTextNode ( $row ["stream_url"] ) );
				$track->appendChild ( $stream_url );
				$permalink = $dom->createAttribute ( "permalink" );
				$permalink->appendChild ( $dom->createTextNode ( $row ["permalink"] ) );
				$track->appendChild ( $permalink );
				$created_at = $dom->createAttribute ( "created_at" );
				$created_at->appendChild ( $dom->createTextNode ( $row ["created_at"] ) );
				$track->appendChild ( $created_at );
				$rating = $dom->createAttribute ( "rating" );
				$ratingValue = isset($row ["rating"]) ? $row ["rating"]: 0;
				$rating->appendChild ( $dom->createTextNode ( $ratingValue ));
				$track->appendChild ( $rating );
				
				$tags_query = "SELECT tag FROM tags WHERE track_id = $track_id_value";
				$tags_result = mysql_query ( $tags_query );
				if (! $tags_result) {
					die ( mysql_error () );
				} elseif ( mysql_num_rows ( $tags_result ) >= 1 ) {
					$tags = $track->appendChild ( $dom->createElement ( 'tags' ) );
					while ( $tag = mysql_fetch_array ( $tags_result, MYSQL_ASSOC ) ) {
						$tags->appendChild ( $dom->createElement ( 'tag', utf8_encode( $tag ["tag"] ) ) );
					}
				}
				
				
			}
			echo $dom->saveXML ();
		}
	}
	private function getTags() {
		header('Content-Type: text/xml');
		$tags_query = "SELECT tag, COUNT(*) AS count FROM tags GROUP BY tag";
		$result = mysql_query ( $tags_query );
		if ($result == false or mysql_num_rows ( $result ) < 1) {
			echo "no data found";
		} else {
			$dom = new DomDocument ( '1.0' );
			$tags = $dom->appendChild ( $dom->createElement ( 'tags' ) );
			while ( $row = mysql_fetch_array ( $result, MYSQL_ASSOC ) ) {
				$tag = $tags->appendChild ( $dom->createElement ( 'tag' ) );
				$tag_text = $dom->createAttribute ( "text" );
				$tag_text->appendChild ( $dom->createTextNode ( utf8_encode( $row ["tag"] ) ) );
				$tag->appendChild ( $tag_text );
				$tag_count = $dom->createAttribute ( "count" );
				$tag_count->appendChild ( $dom->createTextNode ( $row ["count"] ) );
				$tag->appendChild ( $tag_count );
			}
			echo $dom->saveXML ();
		}
	}
	
	private function vote() {
		$rating = $_GET["rating"];
		$track_id = $_GET["track_id"];
		$query = "INSERT INTO rating (track_id, rating) VALUES ($track_id, $rating)";
		$insert_result = mysql_query ( $query );
		if (! $insert_result) {
			die ( mysql_error () );
		}
	}
	
	private function refresh() {
	
		$bHost  = "api.soundcloud.com";
		$bPath = "/users/".$this->soundcloud_username."/tracks?consumer_key=0qR5mT5c85fnuyG0XFXw";
		  
		if(($oHandle = @fsockopen($bHost, 80, $oErrorNo, $oErrorStr, 30)) === false)
		  echo "Fehler: Verbindung fehlgeschlagen. ".$oErrorNo." - ".$oErrorStr."\r\n";
		    
		fputs($oHandle, 'GET '.$bPath.' HTTP/1.1'."\r\n");
		fputs($oHandle, 'Host: '.$bHost."\r\n");
		fputs($oHandle, 'Connection: close'."\r\n");
		
		fputs($oHandle, "\r\n");
		 
		$oReturn = "";
		while(!feof($oHandle)){
		  $oReturn .= fgets($oHandle, 512);
		}
		  
		list($oHeader, $oContent) = explode("\r\n\r\n", $oReturn, 2);
		
		$tracks_xml = simplexml_load_string ( $oContent );
		foreach ( $tracks_xml->track as $track ) {
			$track_id = (int) $track->id;
			$delete_query = "DELETE FROM tracks WHERE track_id = $track_id LIMIT 1";
			$delete_result = mysql_query ( $delete_query );
			if (! $delete_result) {
				die ( mysql_error () );
			}
			$title = (string) $track->title;
			$title = utf8_decode($title);
			$artist = $track->{'label-name'};
			$artist = utf8_decode($artist);
			$duration = (int) $track->duration;
			echo $track_id.": ".$title." artist: ".$artist."<br />";
			$stream_url = (string) $track->{'stream-url'};
			$permalink = (string) $track->{'permalink-url'};
			$created_at =  (string) $track->{'created-at'};
			$created_at = str_replace("T", " ", $created_at);
			$created_at = str_replace("Z", "", $created_at);
			$insert_query = "INSERT INTO tracks (track_id, title, artist, duration, stream_url, permalink, created_at) VALUES ($track_id, '$title', '$artist', $duration, '$stream_url', '$permalink', '$created_at')";
			$insert_result = mysql_query ( $insert_query );
			if (! $insert_result) {
				die ( mysql_error () );
			}
//			$rating = rand (1, 5 );
//			$insert_rating_query = "INSERT INTO rating (track_id, rating) VALUES ($track_id, $rating)";
//			$insert_rating_result = mysql_query ( $insert_rating_query );
//			if (! $insert_rating_result) {
//				die ( mysql_error () );
//			}
			$tag_list = (string) $track->{'tag-list'};
			if (!empty($tag_list)){
				$tags = explode(", ", $tag_list);
				$delete_tags_query = "DELETE FROM tags WHERE track_id = $track_id";
				$delete_tags_result = mysql_query ( $delete_tags_query );
				if (! $delete_tags_result) {
					die ( mysql_error () );
				}
				foreach ( $tags as $tag ){
					$tag = utf8_decode($tag);
					$insert_tag_query = "INSERT INTO tags (track_id, tag) VALUES ($track_id, '$tag')";
					$insert_tag_result = mysql_query ( $insert_tag_query );
					if (! $insert_tag_result) {
						die ( mysql_error () );
					}
				}
			}
		}
	}
}
?>
